package cn.buk.qms.web;

import cn.buk.common.JsonResult;
import cn.buk.common.dto.CommonDto;
import cn.buk.qms.BillUtil;
import cn.buk.tms.dto.CustomerServiceTemplateDto;
import cn.buk.tms.dto.SettlementDto;
import cn.buk.tms.dto.SettlementReportDto;
import cn.buk.tms.sc.SearchBillInfoCriteria;
import cn.buk.tms.sc.SearchFlightOrderCriteria;
import cn.buk.tms.sc.SearchSettlementCriteria;
import cn.buk.qms.service.BasicDataService;
import cn.buk.qms.service.BillService;
import cn.buk.qms.service.CustomerService;
import cn.buk.qms.service.EnterpriseService;
import cn.buk.tms.bill.service.BillCheckService;
import cn.buk.tms.comparator.BillSortComparator;
import cn.buk.tms.entity.base.Airport;
import cn.buk.tms.entity.bill.*;
import cn.buk.tms.entity.misc.*;
import cn.buk.tms.report.service.ReportExportService;
import cn.buk.common.util.DateUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static cn.buk.tms.common.constant.TmsOrderConstant.*;

/**
 *
 * @author yfdai
 * @date 2019-06-28
 */
@RestController
public class BillsController extends BaseController {

    private static final Logger logger = LogManager.getLogger(BillsController.class);

    @Autowired
    private BillService billService;

    @Autowired
    private BillCheckService billCheckService;

    @Autowired
    private BasicDataService basicDataService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ReportExportService reportExportService;

    /**
     * 查找差旅客户的订单
     *
     * @param sc 查询条件
     * @param billType 账单类型
     * @param customerId 客户ID
     * @param bePaid 收款状态
     * @param paymentStatus 支出状态
     * @param payType 账单的付款方式
     * @param reviewed 审核状态
     */
    @RequestMapping(value = {"/searchMyBillInfo.do", "/bills"})
    public CommonDto<BillInfo> searchMyBillInfo(HttpServletRequest request,
                                                @ModelAttribute("sc") SearchBillInfoCriteria sc,
                                                @RequestParam("billType") String billType,
                                                @RequestParam(value = "customerId", required = false) int customerId,
                                                @RequestParam(value = "likeCustomerName", required = false) String likeCustomerName,
                                                @RequestParam(value = "likePsgName", required = false) String likePsgName,
                                                @RequestParam(value = "bePaid", required = false) String bePaid,
                                                @RequestParam(value = "paymentStatus", defaultValue = "-1") int paymentStatus,
                                                @RequestParam(value = "payType", defaultValue = "0") int payType,
                                                @RequestParam(value = "reviewed", defaultValue = "-1") int reviewed,
                                                @RequestParam(value = "ticketStatus", defaultValue = "-1") int ticketStatus) {
        final int enterpriseId = getEnterpriseId(request);

        sc.setBillType(billType);
        sc.setBePaid(bePaid);
        sc.setPayType(payType);
        sc.setReviewed(reviewed);
        sc.setPaymentStatus(paymentStatus);
        sc.setTicketStatus(ticketStatus + "");
        sc.setLikeCustomerName(likeCustomerName);
        sc.setLikePsgName(likePsgName);

        List<BillInfo> dataList = billService.searchMyBillInfo(enterpriseId, sc, customerId);

        CommonDto<BillInfo> commonDto = new CommonDto<>();
        commonDto.setDataList(dataList);
        commonDto.setPage(sc.getPage());

        return commonDto;
    }

    /**
     * 查找待审核账单
     */
    @RequestMapping("/bills/unreviewed")
    public CommonDto<BillInfo> searchUnreviewedBillInfo(HttpServletRequest request,
        @ModelAttribute("sc") SearchBillInfoCriteria sc,
        @RequestParam("billType") String billType,
        @RequestParam(value = "customerId", required = false) int customerId,
        @RequestParam(value = "supplierId", required = false) int supplierId) {
        final int enterpriseId = getEnterpriseId(request);

        sc.setBillType(billType);
        // 未支付
        sc.setBePaid(BillInfo.CUSTOMER_PAYMENT_NOT_RECEIVED);
        // 查看未审核的账单
        sc.setReviewed(0);
        sc.setSupplierId(supplierId);

        List<BillInfo> dataList = billService.searchMyBillInfo(enterpriseId, sc, customerId);

        CommonDto<BillInfo> commonDto = new CommonDto<>();
        commonDto.setDataList(dataList);
        commonDto.setPage(sc.getPage());

        return commonDto;
    }

    /**
     * 查找未审核的机票账单中的机票
     */
    @RequestMapping("/bills/unreviewed/flights")
    public CommonDto<BillFlightTicket> searchUnreviewedFlightTickets(HttpServletRequest request,
                                                                     @ModelAttribute("sc") SearchFlightOrderCriteria sc) {
        final int enterpriseId = getEnterpriseId(request);

        List<BillFlightTicket> tickets = billService.searchUnreviewedFlightTickets(enterpriseId, sc);

        CommonDto<BillFlightTicket> commonDto = new CommonDto<>();
        commonDto.setDataList(tickets);
        commonDto.setPage(sc.getPage());

        return commonDto;
    }

    /**
     * 查找未销账的(已审核的机票账单中的)机票
     */
    @RequestMapping("/bills/unpaid/flights")
    public CommonDto<BillFlightTicket> searchUnpaidFlightTickets(HttpServletRequest request,
        @ModelAttribute("sc") SearchFlightOrderCriteria sc) {
        final int enterpriseId = getEnterpriseId(request);

        List<BillFlightTicket> tickets = billService.searchUnpaidFlightTickets(enterpriseId, sc);

        CommonDto<BillFlightTicket> commonDto = new CommonDto<>();
        commonDto.setDataList(tickets);
        commonDto.setPage(sc.getPage());

        return commonDto;
    }

    /**
     * 自动审核机票账单
     */
    @RequestMapping("/bills/autoReview")
    public JsonResult autoReviewBillInfo(HttpServletRequest request) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return billService.autoReviewBillInfo(enterpriseId, username);
    }

    /**
     * 查找待结算账单
     */
    @RequestMapping("/bills/toSettle")
    public CommonDto<BillInfo> searchBillInfoToSettle(HttpServletRequest request,
        @ModelAttribute("sc") SearchBillInfoCriteria sc,
        @RequestParam("billType") String billType,
        @RequestParam(value = "customerId", required = false) int customerId,
        @RequestParam(value = "supplierId", required = false) int supplierId
    ) {
        final int enterpriseId = getEnterpriseId(request);

        sc.setBillType(billType);
        sc.setSupplierId(supplierId);

        //未收款的
        sc.setBePaid(BillInfo.CUSTOMER_PAYMENT_NOT_RECEIVED);
        sc.setReviewed(1); // 查看已审核的账单
        sc.setSettled(0); // 未结算账单

        List<BillInfo> dataList = billService.searchMyBillInfo(enterpriseId, sc, customerId);

        CommonDto<BillInfo> commonDto = new CommonDto<>();
        commonDto.setDataList(dataList);
        commonDto.setPage(sc.getPage());

        return commonDto;
    }

    /**
     * 检查散客的机票订单的付款状态
     */
    @RequestMapping("/bills/checkFlightOrderPayStatus")
    public JsonResult checkBillFlightOrderPayStatus(HttpServletRequest request) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return billCheckService.checkBillFlightOrderPayStatus(enterpriseId, username);
    }

    /**
     * 批量审核账单
     */
    @RequestMapping("/bills/review/passed")
    public JsonResult reviewBillInfoPassed(HttpServletRequest request,
        @RequestParam("total") double total,
        @RequestParam(value = "billIds[]") int[] billIds) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return billService.batchReviewBillInfos(enterpriseId, username, billIds, total);
    }

    /**
     * 下载账单
     */
    @RequestMapping(value = {"/downloadBillInfo.do", "/bills/download"})
    public void downloadMyBillInfo(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute("sc") SearchBillInfoCriteria sc,
        @RequestParam("billType") final String billType,
        @RequestParam(value = "customerId", defaultValue = "0") final int customerId,
        @RequestParam(value = "reviewed", defaultValue = "-1") int reviewed,
        @RequestParam(value = "settled", defaultValue = "-1") int settled,
        @RequestParam(value = "bePaid", required = false) String bePaid,
        @RequestParam(value = "payType", defaultValue = "0") int payType,
        @RequestParam(value = "format", defaultValue = "0") final int format // 下载格式  0 - 默认格式，1 - 格式一
    ) {
        final int enterpriseId = getEnterpriseId(request);

        sc.setBillType(billType);
        sc.setReviewed(reviewed);
        sc.setBePaid(bePaid);
        sc.setSettled(settled);
        sc.setPayType(payType);

        //输出
        PrintWriter out;
        try {
            String filename = "bill-info-" + DateUtil.formatDate(DateUtil.getCurDateTime(), "yyyyMMddHHmmss") + ".csv";
            response.setHeader("Content-Disposition", "inline; filename=" + filename);
            response.setContentType("application/octet-stream");

            // 加上UTF-8文件的标识字符
            response.getOutputStream().write(
                new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));

            List<Airport> airports = basicDataService.searchAirports();
            List<Customer> customers = customerService.getAllCustomers(enterpriseId);

            if (format == 0 || format == 1) {
                // 默认的2个模板
                billService.exportDefaultFormatBills(sc, format, enterpriseId, customerId, airports, customers, out);
            } else {
                //导出自定义模板
                exportBillCustomFormat(sc, format, enterpriseId, customerId, airports, out);
            }

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 按照自定义格式导出账单
     */
    private void exportBillCustomFormat(SearchBillInfoCriteria sc, final int format,
                                        final int enterpriseId, final int customerId,
                                        List<Airport> airports,
                                        PrintWriter out) {

        //准备下载格式
        DataFieldExportTemplate templateInfo = enterpriseService.searchDataTemplate(enterpriseId, format);
        if (templateInfo == null) {
            return;
        }
        List<DataFieldExportInfo> exportInfos = templateInfo.getExportFields();

        StringBuilder sb = BillUtil.exportTitle(exportInfos);

        out.print(sb);
        out.flush();

        if (customerId < 1) {
            out.print("自定义模板导出时需要先选择客户，再导出。根据不同的客户服务费模板，在导出时系统会判断是否合并服务费。");
            out.flush();
            return;
        }

        sc.setPageNo(1);
        sc.setPageSize(5000);

        // 根据账单类型排序
        sc.setOrderBy(2);

        boolean b = true;
        List<BillInfo> infos = null;
        while (b) {
            b = false;

            List<BillInfo> infos0 = billService
                    .searchMyBillInfo(enterpriseId, sc, customerId, true);
            if (infos == null) {
                infos = infos0;
            } else {
                infos.addAll(infos0);
            }

            if (sc.getPageNo() < sc.getPage().getPageTotal()) {
                b = true;
                sc.setPageNo(sc.getPageNo() + 1);
            }
        }

        //排序：机票、退票、改签、酒店、火车、服务
        //将退票和改签与相关的机票排在一起
        doSortBills(infos);

        //服务费是否单独显示
        //1：单独显示
        //0：不单独显示，与航司销售价、航司退票费、航司改签费合并
        Optional<CustomerServiceTemplateDto> tpl = enterpriseService.searchServiceTemplateByCustomer(enterpriseId, customerId);
        final int reportShowFee = tpl.map(CustomerServiceTemplateDto::getReportShowFee).orElse(1);

        for (BillInfo info : infos) {
            sb = BillUtil.exportContent(info, exportInfos, airports, reportShowFee);
            out.print(sb);
        }
        out.flush();
    }

    /**
     * //排序：机票、退票、改签、酒店、火车、服务
     *         //将退票和改签与相关的机票排在一起
     */
    private void doSortBills(List<BillInfo> infos) {
        infos.sort(new BillSortComparator());
        for(int i = 0; i < infos.size(); i++) {
            BillInfo billInfo1 = infos.get(i);
            if (!billInfo1.getBillType().equalsIgnoreCase(BILL_TYPE_FLIGHT)) {
                continue;
            }

            final String flightOrderNo1 = billInfo1.getFlightOrderNo();
            if (flightOrderNo1.length() == 0) {
                continue;
            }

            for(int j = i+1; j < infos.size(); j++) {
                BillInfo billInfo2 = infos.get(j);

                if (billInfo2.getBillType().equalsIgnoreCase(BILL_TYPE_FLIGHT_REFUND)
                        || billInfo2.getBillType().equalsIgnoreCase(BILL_TYPE_FLIGHT_CHANGE)) {

                    final String flightOrderNo2 = billInfo2.getFlightOrderNo();

                    if (flightOrderNo1.equalsIgnoreCase(flightOrderNo2)) {
                        //账单号相等
                        infos.remove(j);
                        infos.add(i+1, billInfo2);
                    }
                }
            }
        }

    }

    /**
     * 创建结算单
     */
    @RequestMapping("/bills/settlement/create")
    public JsonResult createSettlement(HttpServletRequest request,
        @RequestParam("customerId") int customerId,
        @RequestParam(value = "settlementId", defaultValue = "0") int settlementId,
        @RequestParam("settlementNo") String settlementNo,
        @RequestParam("settlementName") String settlementName,
        @RequestParam("total") double total,
        @RequestParam(value = "billIds[]") Integer[] billIds) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);
        return billService.createSettlement(enterpriseId, username, customerId, settlementId, settlementNo, settlementName, total, billIds);
    }

    /**
     * 批量创建结算单
     */
    @RequestMapping("/bills/settlement/batchCreate")
    public JsonResult batchCreateSettlement(HttpServletRequest request,
        @RequestParam("beginDate") Date beginDate,
        @RequestParam("endDate") Date endDate,
        @RequestParam(value = "customerId", defaultValue = "-1") int customerId,
        @RequestParam(value = "prefix", defaultValue = "") String prefix) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);
        return billService.batchCreateSettlement(enterpriseId, username, beginDate, endDate, customerId, prefix);
    }

    /**
     * 查找结算单
     */
    @RequestMapping("/settlements")
    public CommonDto<SettlementSheet> searchSettlements(HttpServletRequest request,
                                                        @ModelAttribute("sc") SearchSettlementCriteria sc,
                                                        @RequestParam(value = "bePaid", required = false) String bePaid,
                                                        @RequestParam(value = "likeCustomerName", required = false) String likeCustomerName) {
        final int enterpriseId = getEnterpriseId(request);

        sc.setBePaid(bePaid);
        sc.setLikeCustomerName(likeCustomerName);

        List<SettlementSheet> dataList = billService.searchSettlements(enterpriseId, getUserId(request), sc);

        CommonDto<SettlementSheet> commonDto = new CommonDto<>();
        commonDto.setDataList(dataList);
        commonDto.setPage(sc.getPage());

        return commonDto;
    }

    /**
     * 查找未付款的结算单
     */
    @RequestMapping("/settlements/unpaid")
    public List<SettlementSheet> searchUnpaidSettlements(HttpServletRequest request,
        @RequestParam(value = "customerId") int customerId) {
        return billService.searchUnpaidSettlements(getEnterpriseId(request), customerId);
    }

    /**
     * 查找结算单详情
     */
    @RequestMapping("/settlement/{id}")
    public SettlementDto searchSettlementDetail(HttpServletRequest request,
        @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementDetail(enterpriseId, id);
    }

    /**
     * 结算单报表
     */
    @RequestMapping("/settlement/{id}/report")
    public SettlementReportDto searchSettlementReport(HttpServletRequest request,
        @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementReport(enterpriseId, id);
    }

    /**
     * 结算单报表 - 下载
     */
    @RequestMapping("/settlement/{id}/report/download")
    public void downloadSettlementReport(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        SettlementReportDto dto =  billService.searchSettlementReport(enterpriseId, id);

        //输出
        PrintWriter out;
        try {
            String filename = "settlement-report-" + DateUtil.formatDate(DateUtil.getCurDateTime(), "yyyyMMddHHmmss") + ".csv";
            response.setHeader("Content-Disposition", "inline; filename=" + filename);
            response.setContentType("application/octet-stream");

            // 加上UTF-8文件的标识字符
            response.getOutputStream().write(
                new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));

            StringBuilder sb = SettlementReportDto.exportTitle0();
            out.print(sb);
            out.flush();

            sb = SettlementReportDto.exportContent0(dto);
            out.print(sb);
            out.flush();

            sb = SettlementReportDto.exportTitle1();
            out.print(sb);
            out.flush();

            sb = SettlementReportDto.exportContent1(dto);
            out.print(sb);
            out.flush();

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 结算单报表 - 下载(使用模板格式）
     */
    @RequestMapping("/settlement/{id}/report/downloadByTpl")
    public void downloadSettlementReportByTpl(HttpServletRequest request,
                                         HttpServletResponse response,
                                         @PathVariable("id") int id,
                                              @RequestParam(value = "templateId", defaultValue = "0") final int templateId0) {
        final int enterpriseId = getEnterpriseId(request);
        SettlementReportDto dto = billService.searchSettlementReport(enterpriseId, id);

        //输出
        try {
            ServletOutputStream out = response.getOutputStream();
            String filename = "settlement-report-" + DateUtil.formatDate(DateUtil.getCurDateTime(), "yyyyMMddHHmmss") + ".xlsx";
            response.setHeader("Content-Disposition", "inline; filename=" + filename);
            response.setContentType("application/ms-excel;charset=UTF-8");

            Workbook workbook = WorkbookFactory.create(true); //xlsx
//            Workbook workbook = WorkbookFactory.create(false); //xls
            Sheet sheet = workbook.createSheet();

            final int templateId = templateId0 > 0 ? templateId0: dto.getReportTemplateId();
            if (templateId == 3) {
                //此格式需要将保险合并到机票一起（对原始的数据录入有要求）
                billService.prepareSettlementReportTpl3(dto);
            }

            final double exportedTotal = reportExportService.exportSettlementToExcel(enterpriseId, dto, sheet, templateId);
            if (exportedTotal != dto.getAmount()) {
                logger.error("settlement's export total is {}, but total should be {}.({})", exportedTotal, dto.getAmount(), dto.getSettlementNo());
            } else {
                logger.info("{} = {}", exportedTotal, dto.getAmount());
            }


            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 查找结算单中的账单
     */
    @RequestMapping("/settlement/{id}/bills")
    public List<BillInfo> searchSettlementDetail(HttpServletRequest request,
        @PathVariable("id") int id,
        @RequestParam(value = "billNo", defaultValue = "") String billNo,
        @RequestParam(value = "orderNo", defaultValue = "") String orderNo,
        @RequestParam(value = "flightOrderNo", defaultValue = "") String flightOrderNo,
        @RequestParam(value = "psgName", defaultValue = "") String psgName,
        @RequestParam(value = "billDate", defaultValue = "") String billDate) {
        return billService.searchSettlementBills(getEnterpriseId(request), id, billNo, orderNo, billDate, flightOrderNo, psgName);
    }

    /**
     * 查找结算单中的机票账单对应的票号
     */
    @RequestMapping("/settlement/{id}/bills/tickets")
    public List<BillFlightTicket> searchSettlementBillFlightTicket(HttpServletRequest request,
        @PathVariable("id") int id,
        @RequestParam(value = "psgName", defaultValue = "") String psgName,
        @RequestParam(value = "ticketNo", defaultValue = "") String ticketNo) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementBillFlightTicket(enterpriseId, id, psgName.toUpperCase(), ticketNo);
    }

    /**
     * 查找结算单中的退票账单对应的票号
     */
    @RequestMapping("/settlement/{id}/bills/refunds")
    public List<BillFlightRefundTicket> searchSettlementBillFlightRefundTicket(HttpServletRequest request,
                                                                               @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementRefunds(enterpriseId, id);
    }

    /**
     * 查找结算单中的改签账单对应的票号
     */
    @RequestMapping("/settlement/{id}/bills/changes")
    public List<BillChangeOrder> searchSettlementBillChangeOrders(HttpServletRequest request,
                                                                  @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementChanges(enterpriseId, id);
    }

    /**
     * 查找结算单中的增值服务账单
     */
    @RequestMapping("/settlement/{id}/bills/vas")
    public List<BillVasOrder> searchSettlementBillVases(HttpServletRequest request,
        @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementVases(enterpriseId, id);
    }

    /**
     * 查找结算单中的用车账单
     */
    @RequestMapping("/settlement/{id}/bills/rentalCars")
    public List<BillRentalCarOrder> searchSettlementBillRentalCars(HttpServletRequest request,
                                                        @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementBillRentalCars(enterpriseId, id);
    }

    /**
     * 查找结算单中的酒店
     */
    @RequestMapping("/settlement/{id}/bills/hotel")
    public List<BillHotelBooking> searchSettlementBillHotels(HttpServletRequest request,
                                                             @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementHotels(enterpriseId, id);
    }

    /**
     * 查找结算单中的火车票
     */
    @RequestMapping("/settlement/{id}/bills/train")
    public List<BillTrainTicket> searchSettlementBillTrains(HttpServletRequest request,
        @PathVariable("id") int id) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementTrains(enterpriseId, id);
    }

    /**
     * 查找结算单详情
     */
    @RequestMapping("/settlement/{id}/history")
    public List<OperationLog> searchSettlementHistory(HttpServletRequest request,
                                                      @PathVariable("id") int id
    ) {
        final int enterpriseId = getEnterpriseId(request);
        return billService.searchSettlementHistory(enterpriseId, id);
    }

    /**
     * 从结算单移除一个账单
     */
    @RequestMapping("/settlement/{id}/remove/{billNo}")
    public JsonResult removeBillOfSettlement(HttpServletRequest request,
        @PathVariable("id") int id,
        @PathVariable("billNo") String billNo
    ) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);
        return billService.removeBillOfSettlement(enterpriseId, username, id, billNo);
    }

    /**
     * 从结算单移除所有账单
     */
    @PostMapping("/settlement/{id}/removeAllBills")
    public JsonResult removeAllBillsFromSettlement(HttpServletRequest request,
                                             @PathVariable("id") int id
    ) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);
        return billService.removeAllBillsFromSettlement(enterpriseId, username, id);
    }

    /**
     * 修改结算单的名称
     */
    @RequestMapping("/settlement/{id}/name")
    public JsonResult updateSettlementName(HttpServletRequest request,
        @PathVariable("id") int id,
        @RequestParam("name") String settlementName) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);
        return billService.updateSettlementName(enterpriseId, username, id, settlementName);
    }

    /**
     * 调整结算单的金额（纠错用）
     */
    @RequestMapping("/settlement/{id}/adjustAmount")
    public JsonResult adjustSettlementAmount(HttpServletRequest request,
        @PathVariable("id") int id,
        @RequestParam("amount") double amount,
        @RequestParam("remark") String remark
    ) {
        final int enterpriseId = getEnterpriseId(request);
        final int userId = getUserId(request);
        final String username = getUsername(request);
        return billService.adjustSettlementAmount(enterpriseId, userId, username, id, amount, remark);
    }

    /**
     * 检查账单的intlTicket属性（临时代码）
     */
    @RequestMapping("/bills/checkIntlTicket")
    public JsonResult checkBillIntlTicket(HttpServletRequest request) {
        final int enterpriseId = getEnterpriseId(request);

        return billCheckService.checkBillIntlTicket(enterpriseId);
    }
    
}
